package urlsvr

import (
	"fmt"
	"lnzw/common/banner"
	"lnzw/common/proto/common_gen"
	"lnzw/engine/cluster"
	"lnzw/engine/http"
	"lnzw/engine/log"
	"lnzw/engine/pprofile"
	"lnzw/engine/work"
	"lnzw/engine/yaml"
	"lnzw/server/logic/cmd"
	"lnzw/server/logic/node"
	_ "lnzw/server/urlsvr/init"
	"lnzw/server/urlsvr/router"

	"go.uber.org/zap"
)

type UrlServer struct {
	httpServer *http.HttpServer
	close      chan struct{}
}

func (g *UrlServer) Start() {
	defer func() {
		if err := recover(); err != nil {
			log.Logger.Error("UrlServer Start error", zap.Any("err", err))
		}
	}()
	g.close = make(chan struct{})
	banner := banner.NewDefaultBanner()
	fmt.Println(banner.Get("URL SERVER"))
	pprofile.Setup()
	//安装日志
	log.Setup()
	//读取配置
	yaml.Setup()
	//工作队列
	work.Setup()
	//cmd
	cmd.Setup()
	//集群配置
	cluster.Setup()
	cluster.DEFAULT.Init(cluster.ETCD, &node.UrlNode{
		DefaultNode: cluster.DefaultNode{Id: 1, Data: &node.UrlNodeData{}},
	})
	cluster.DEFAULT.ObserveNodeType(int32(common_gen.ServerType_gate))
	//启动服务器
	g.httpServer = http.NewGinServer()
	router.SetupRouter(g.httpServer)
	go g.httpServer.Start()
	<-g.close
}

func (g *UrlServer) Stop() {
	if g.close != nil {
		g.close <- struct{}{}
	}
}
